@*
    物料产品添加/编辑页面
*@
@{
    ViewData["Title"] = "物料产品管理";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@ViewData["Title"]</title>
    <link href="~/layui/css/layui.css" rel="stylesheet" />
    <style>
        .layui-form-item .layui-input-inline {
            width: 180px;
        }
        .image-upload {
            width: 100px;
            height: 100px;
            border: 1px dashed #ccc;
            text-align: center;
            line-height: 100px;
            cursor: pointer;
            position: relative;
        }
        .image-upload input[type="file"] {
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            left: 0;
            top: 0;
            cursor: pointer;
        }
        .upload-preview {
            width: 100px;
            height: 100px;
            object-fit: cover;
            display: none;
        }
        .form-container {
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    @Html.AntiForgeryToken()
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">
                <span id="pageTitle">新增物料</span>
            </div>
            <div class="layui-card-body">
                <div class="form-container">
                    <form class="layui-form" lay-filter="materialForm" id="materialForm">
                        <input type="hidden" name="id" id="materialId">
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">物料编码</label>
                            <div class="layui-input-block">
                                <div class="layui-input-inline" style="width: 280px;">
                                    <input type="text" name="materielCode" lay-verify="materielCode" placeholder="请输入物料编码" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-input-inline" style="width: 80px;">
                                    <input type="checkbox" name="autoGenCode" lay-skin="switch" lay-text="自动|手动" lay-filter="autoGenCode">
                                </div>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">物料名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="materielName" lay-verify="materielName" placeholder="请输入物料名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">规格型号</label>
                            <div class="layui-input-block">
                                <textarea name="specifications" placeholder="请输入规格型号" class="layui-textarea"></textarea>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">单位</label>
                            <div class="layui-input-block">
                                <select name="unitsId" lay-verify="required">
                                    <option value="">请选择单位</option>
                                    <option value="个">个</option>
                                    <option value="件">件</option>
                                    <option value="块">块</option>
                                    <option value="箱">箱</option>
                                    <option value="盒">盒</option>
                                    <option value="瓶">瓶</option>
                                    <option value="袋">袋</option>
                                    <option value="kg">千克</option>
                                    <option value="g">克</option>
                                    <option value="t">吨</option>
                                    <option value="L">升</option>
                                    <option value="mL">毫升</option>
                                    <option value="m">米</option>
                                    <option value="cm">厘米</option>
                                    <option value="mm">毫米</option>
                                    <option value="m²">平方米</option>
                                    <option value="m³">立方米</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">物料类型</label>
                            <div class="layui-input-block">
                                <input type="radio" name="materielTypePid" value="0" title="物料" checked>
                                <input type="radio" name="materielTypePid" value="1" title="产品">
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">所属分类</label>
                            <div class="layui-input-block">
                                <select name="materielTypeld" lay-verify="required">
                                    <option value="">请选择分类</option>
                                    <option value="1">原材料</option>
                                    <option value="2">半成品</option>
                                    <option value="3">成品</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">是否启用</label>
                            <div class="layui-input-block">
                                <input type="radio" name="isNo" value="1" title="启用" checked>
                                <input type="radio" name="isNo" value="0" title="禁用">
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">安全库存</label>
                            <div class="layui-input-block">
                                <input type="radio" name="isSecure" value="1" title="是">
                                <input type="radio" name="isSecure" value="0" title="否" checked>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">物料图片</label>
                            <div class="layui-input-block">
                                <input type="hidden" name="materielUrl">
                                <div class="image-upload" id="imageUpload">
                                    <i class="layui-icon">&#xe67c;</i>
                                    <input type="file" accept="image/*" id="imageFile">
                                </div>
                                <img id="imagePreview" class="upload-preview">
                            </div>
                        </div>
                        
                        <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
                            <button type="button" class="layui-btn" lay-submit lay-filter="submitForm">保存</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="~/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer', 'upload'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var upload = layui.upload;
            var $ = layui.jquery;

            // 获取URL参数
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            }

            // 判断是否为编辑模式
            var materialId = getUrlParam('id');
            var isEdit = materialId != null;
            var materialData = null;

            // 设置页面标题
            if (isEdit) {
                $('#pageTitle').text('编辑物料');
                $('#materialId').val(materialId);
                loadMaterialData(materialId);
            } else {
                $('#pageTitle').text('新增物料');
            }

            // 加载物料数据
            function loadMaterialData(id) {
                var loadIndex = layer.load();
                $.ajax({
                    url: '/Material/GetMaterial',
                    type: 'GET',
                    data: { id: id },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            materialData = res.data;
                            bindFormData(materialData);
                        } else {
                            layer.msg('获取物料数据失败: ' + res.message);
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        console.error('获取物料数据错误:', xhr);
                        layer.msg('服务器错误: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                    }
                });
            }

            // 绑定表单数据
            function bindFormData(data) {
                // 先设置表单值
                form.val('materialForm', data);
                
                // 处理图片显示
                if (data.materielUrl) {
                    $('#imagePreview').attr('src', data.materielUrl).show();
                    $('#imageUpload').hide();
                }
                
                // 重新渲染表单组件
                setTimeout(function() {
                    form.render();
                }, 100);
            }

            // 图片上传处理
            $('#imageFile').on('change', function (e) {
                var file = e.target.files[0];
                if (file) {
                    // 验证文件大小 (2MB)
                    if (file.size > 2 * 1024 * 1024) {
                        layer.msg('图片大小不能超过2MB');
                        return;
                    }
                    
                    // 验证文件类型
                    if (!file.type.match(/^image\/(jpeg|jpg|png|gif)$/)) {
                        layer.msg('只支持jpg、png、gif格式的图片');
                        return;
                    }
                    
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $('#imagePreview').attr('src', e.target.result).show();
                        $('#imageUpload').hide();
                        $('input[name="materielUrl"]').val(e.target.result);
                    };
                    reader.readAsDataURL(file);
                }
            });

            // 自定义验证规则
            form.verify({
                materielCode: function(value) {
                    if (!value) {
                        return '物料编码不能为空';
                    }
                    if (value.length < 3) {
                        return '物料编码长度不能少于3位';
                    }
                    if (!/^[A-Za-z0-9]+$/.test(value)) {
                        return '物料编码只能包含字母和数字';
                    }
                },
                materielName: function(value) {
                    if (!value) {
                        return '物料名称不能为空';
                    }
                    if (value.length > 100) {
                        return '物料名称长度不能超过100个字符';
                    }
                }
            });

            // 表单提交
            form.on('submit(submitForm)', function (formData) {
                var loadIndex = layer.load();
                var url, postData;
                
                postData = formData.field;
                
                if (isEdit) {
                    url = '/Material/UpdateMaterial';
                    postData.id = materialData.id;
                } else {
                    url = '/Material/CreateMaterial';
                    delete postData.id;
                }
                
                // 移除自动生成开关字段
                delete postData.autoGenCode;
                
                // 转换数字字段
                postData.materielTypePid = parseInt(postData.materielTypePid);
                postData.materielTypeld = parseInt(postData.materielTypeld);
                postData.isNo = parseInt(postData.isNo);
                postData.isSecure = parseInt(postData.isSecure);
                if (isEdit) {
                    postData.id = parseInt(postData.id);
                }

                console.log("提交数据:", url, postData);

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: {
                        ...postData,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            layer.msg('操作成功', {
                                icon: 1,
                                time: 2000
                            }, function() {
                                // 返回列表页面或关闭窗口
                                if (window.parent && window.parent.layer) {
                                    window.parent.layer.closeAll();
                                    if (window.parent.layui && window.parent.layui.table) {
                                        window.parent.layui.table.reload('materialTable');
                                    }
                                } else {
                                    window.location.href = '/Material/Index';
                                }
                            });
                        } else {
                            layer.msg('操作失败: ' + res.message);
                        }
                    },
                    error: function (xhr) {
                        console.error('提交请求错误:', xhr);
                        layer.close(loadIndex);
                        layer.msg('服务器错误: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                    }
                });
                return false;
            });

            // 取消按钮
            $('#cancelBtn').on('click', function () {
                if (window.parent && window.parent.layer) {
                    window.parent.layer.closeAll();
                } else {
                    window.location.href = '/Material/Index';
                }
            });

            // 监听自动生成编码开关
            form.on('switch(autoGenCode)', function(data) {
                if (data.elem.checked) {
                    // 自动生成编码
                    $.ajax({
                        url: '/Material/GenerateMaterialCode',
                        type: 'GET',
                        success: function(res) {
                            if (res.success) {
                                form.val('materialForm', {
                                    'materielCode': res.code
                                });
                            }
                        },
                        error: function(xhr) {
                            console.error('获取编码请求错误:', xhr);
                            layer.msg('获取编码失败: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>